import { Injectable } from '@angular/core';
import { LoadingService } from 'ng-devui/loading'
import { DrawerService, IDrawerOpenResult } from 'ng-devui/drawer';
import { OrderComponent } from '../home/order/order.component'
import { OrderManageService } from '../@core/order-manage.service'
import { AuthGuardService } from '../@core/auth-guard-service.guard'
import { DialogService } from 'ng-devui'
import { Router } from '@angular/router'
import { SelectAvatarTypeComponent } from '../home/select-avatar-type/select-avatar-type.component'

@Injectable({
  providedIn: 'root'
})
export class GetCollectionService {
  drawer: IDrawerOpenResult;
  userId = parseInt(localStorage.getItem('userId'))
  showLoading: any

  constructor(private drawerService: DrawerService,
    private authGuardService: AuthGuardService,
    private loadingService: LoadingService,
    private dialogService: DialogService,
    private orderManageService: OrderManageService,
    private router: Router) { }

  timeTransform(time) {
    var date = new Date(time)
    var Y = date.getFullYear() + '-'
    var M =
      (date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1) + "-";
    var D =
      (date.getDate() < 10
        ? "0" + (date.getDate())
        : date.getDate()) + " ";
    var h = date.getHours() > 9 ? date.getHours(): "0"+ date.getHours() ;
    var m = date.getMinutes() > 9 ? date.getMinutes(): "0"+ date.getMinutes();
    var s = date.getSeconds() > 9 ? date.getSeconds(): "0"+ date.getSeconds();
    return Y + M + D + h + ":" + m + ":" + s;
  }

  applyFun(id, subId) {
    let orderData;
    this.showLoading = this.loadingService.open()
    this.orderManageService.applyCollection(this.userId, id, subId).subscribe(
      (succRes) => {
        this.showLoading.loadingInstance.close()
        if (succRes?.code === 0) {
          orderData = succRes.data
          orderData.createdTime = this.timeTransform(succRes.data.createdTime)
          this.openDrawer(id, subId, orderData)
        } else {
          if (succRes.data?.Identity_Verification === false) {
            this.openEnquireDialog()
          } else {
            this.authGuardService.showModalPanel('warning', succRes.msg)
          }
        }
      },
      (errRes) => {
        this.showLoading.loadingInstance.close()
        this.openStandardDialog()
      }
    )
  }

  openStandardDialog(collectionID?: string, dialogtype?: string) {
    const results = this.dialogService.open({
      id: 'dialog-service',
      width: '450px',
      maxHeight: '600px',
      content: SelectAvatarTypeComponent,
      backdropCloseable: true,
      dialogtype: dialogtype,
      buttons: [],
      data: {
        closeDialog: (value: boolean) => {
          results.modalInstance.hide()
        },
        collectionID,
      }
    })
  }

  openEnquireDialog() {
    const results = this.dialogService.open({
      title: '提示',
      dialogtype: 'warning',
      content: '您尚未完成实名认证，无法购买',
      buttons: [
        {
          cssClass: 'primary',
          text: '去验证',
          handler: ($event: Event) => {
            var url = this.router.serializeUrl(
              this.router.createUrlTree(['/userVerification'])
            )
            window.open('#' + url, '_blank')
            results.modalInstance.hide()
          }
        },
        {
          cssClass: 'primary',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide()
          }
        }
      ]
    })
  }

  openPublishDialog(item) {
    const { collectionIndex, collectionName, subCollectionIndex } = item
    const results = this.dialogService.open({
      title: '提示',
      dialogtype: 'warning',
      content: '是否确认购买“' + collectionName + '”？',
      buttons: [
        {
          cssClass: 'primary',
          text: '确认',
          handler: ($event: Event) => {
            this.applyFun(collectionIndex, subCollectionIndex)
            results.modalInstance.hide()
          }
        },
        {
          cssClass: 'primary',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide()
          }
        }
      ]
    })
  }

  openDrawer(collectionIndex: string, subCollectionIndex: string, orderData) {
    this.drawer = this.drawerService.open({
      drawerContentComponent: OrderComponent,
      width: '31.25%',
      zIndex: 1000,
      isCover: true,
      fullScreen: true,
      backdropCloseable: false,
      escKeyCloseable: false,
      position: 'right',
      bodyScrollable: true,
      data: {
        collectionIndex,
        orderData,
        subCollectionIndex,
        close: (event) => {
          this.drawer.drawerInstance.hide();
        }
      }
    })
  }
}
